package com.base.self.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.base.result.PageUtils;
import com.base.result.ResponseResult;
import com.base.result.ResponseResultUtils;
import com.base.self.common.SelfRuntimeException;
import com.base.self.dto.selfAddress.SelfAddressWebListDTO;
import com.base.self.dto.selfAddress.SelfAddressWebUpdateDTO;
import com.base.self.entity.SelfAddress;
import com.base.self.mapper.SelfAddressMapper;
import com.base.self.service.ISelfAddressService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import java.util.Optional;

/**
 * <p>
 * 收货地址 服务实现类
 * </p>
 *
 * @author XiFYuW
 * @since 2020-11-17
 */
@Service
public class SelfAddressServiceImpl extends ServiceImpl<SelfAddressMapper, SelfAddress> implements ISelfAddressService {

    private final SelfAddressMapper selfAddressMapper;

    public SelfAddressServiceImpl(SelfAddressMapper selfAddressMapper) {
        this.selfAddressMapper = selfAddressMapper;
    }

    @Override
    @Transactional(readOnly = true)
    public ResponseResult selfAddressWebList(SelfAddressWebListDTO selfAddressWebListDTO) {
        final Map<String, Object> data = PageUtils.getDateMap(() -> page(PageUtils.getPage(
                new Page<>(), selfAddressWebListDTO.getOffset(), selfAddressWebListDTO.getLimit()),
                new LambdaQueryWrapper<SelfAddress>()
                        .eq(SelfAddress::getIsDel, 0)
                        .eq(StringUtils.isNotEmpty(selfAddressWebListDTO.getUserMobile()), SelfAddress::getUserMobile, selfAddressWebListDTO.getUserMobile())
                        .orderByDesc(SelfAddress::getCreateTime)));
        return ResponseResultUtils.getResponseResultS("查询成功", data);
    }

    @Override
    @Transactional
    public ResponseResult selfAddressWebUpdate(SelfAddressWebUpdateDTO selfAddressWebUpdateDTO) {
        final SelfAddress selfAddress = selfAddressMapper.selectById(selfAddressWebUpdateDTO.getId());
        Optional.ofNullable(selfAddress).orElseThrow(() -> new SelfRuntimeException(ResponseResultUtils.getResponseResultF("地址信息错误")));

        selfAddress.setUpdateTime(DateUtil.date());
        selfAddress.setAddress(selfAddressWebUpdateDTO.getAddress());
        selfAddress.setMobile(selfAddressWebUpdateDTO.getMobile());
        selfAddress.setName(selfAddressWebUpdateDTO.getName());
        return ResponseResultUtils.getResponseResultS("修改成功");
    }
}
